<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/20
 * Time: 17:17
 */

namespace zhtfrontend\controllers;


use common\components\helpers\Fun;
use common\models\datas\Customer;
use common\models\datas\Student;
use yii\db\Query;
use zhtfrontend\components\bases\BaseController;
use yii\data\Pagination;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\ClassManageAttribute;
use zhtfrontend\models\datas\ClassManageGoods;
use zhtfrontend\models\datas\ClassManageTeacher;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Goods;
use zhtfrontend\models\datas\GoodsPrice;
use zhtfrontend\models\datas\Mechanic;
use zhtfrontend\models\datas\OrdersItemsRelation;
use zhtfrontend\models\datas\StudentCheck;
use zhtfrontend\models\datas\Teacher;

class RenewalrateController extends BaseController
{
    //班主任列表
    public function actionIndex()
    {
        $get = \Yii::$app->request->get();
        $model = Mechanic::find()->select(['id','name'])->where(['status'=>1]);
        $page = \Yii::$app->request->get('page');
        $pages = new Pagination(['totalCount' => $model->count(), 'pageSize' => 14, 'params' => \Yii::$app->request->get()]);
        $data = $model->offset($pages->offset)->limit($pages->limit)->asArray()->all();
        $start = !empty($get['satrtdate'])?strtotime(trim($get['satrtdate'])):0;
        $end = !empty($get['enddate'])?strtotime(trim($get['enddate'])."+1 day"):0;
        foreach ($data as $key=>$item){
            $classIds = ClassManage::find()->select('class_id')->where(['mechanic_id'=>$item['id']])->column();
            $count = $this->getCount($classIds,$start,$end);
            $data[$key]['count'] = $count; //总人数
            $data[$key]['appointmentCount'] = count($this->getCounttype($classIds,'appointment',$start,$end)); //预约人数
            $renewCount = count($this->getCounttype($classIds,'renew',$start,$end)); //预约人数
            $data[$key]['renewCount'] = $renewCount; //预约人数
            $data[$key]['renewalrate'] = 0;
            if($count > 0 && $renewCount>0){
                $data[$key]['renewalrate'] = round($renewCount/$count,4)*100 .'%';
            }
            $retreatcount = $this->getRetreatcount($classIds,$start,$end);
            $data[$key]['retreatcount'] = $retreatcount; //退课人数
//            $endcount = ClassStudent::find()->where(['class_manage_id'=>$classIds,'status'=>2])->count();
//            $data[$key]['endcount'] = $endcount; //结课人数
//            $turncount = ClassStudent::find()->where(['class_manage_id'=>$classIds,'status'=>5])->count();
//            $data[$key]['turncount'] = $turncount; //转课人数
        }

//       print_r($data);die;
        //$data = Fun::asArray($data, ['menu_name','is_top','operate']);
        return $this->render('index', ['data' => $data, 'pages' => $pages,'page'=>$page]);
    }

    public function getOrderitemsIds($start,$end){
        $model = (new Query())
            ->select('oi.id')
            ->from('{{%orders_items}} oi' )
            ->leftJoin('{{%orders}} o','o.id= oi.orders_id');
            if($start > 0 && $end == 0){
                $model->where(['>','o.pay_time',$start]);
            }
           if($start == 0 && $end > 0){
             $model->where(['<','o.pay_time',$end]);
            }
            if($start > 0 && $end > 0){
                $model->where(['between','o.pay_time',$start,$end]);
            }
        $items_ids = $model->column(Fun::getSiteDb());
        return $items_ids;
    }

    public function actionView(){
        $id = \Yii::$app->request->get('id'); //机构id
        $get = \Yii::$app->request->get();
        $start = !empty($get['satrtdate'])?strtotime(trim($get['satrtdate'])):0;
        $end = !empty($get['enddate'])?strtotime(trim($get['enddate'])."+1 day"):0;
        $model = (new Query())
            ->select('ct.teacher_id')
            ->from('{{%class_student}} cs' )
            ->leftJoin('{{%class_manage}} cm','cm.class_id= cs.class_manage_id')
            ->leftJoin('{{%class_manage_teacher}} ct','ct.class_id = cm.class_id')
            ->where(['cs.status'=>[0,1,2,4,5,6],'cm.mechanic_id'=>$id]);
            if($start>0 && $end == 0){
                $ids = $this->getOrderitemsIds($start,0);
                $model->andWhere(['cs.order_sales_id'=>$ids]);
            }
            if($start == 0 && $end >0){
                $ids = $this->getOrderitemsIds(0,$end);
                $model->andWhere(['cs.order_sales_id'=>$ids]);
            }
            if($start > 0 && $end >0){
                $ids = $this->getOrderitemsIds($start,$end);
                $model->andWhere(['cs.order_sales_id'=>$ids]);
            }
          $model->groupBy('cs.class_manage_id');
         $teacher_ids = $model->column(Fun::getSiteDb());
        $teacher_list = Teacher::find()->select(['id','name'])->where(['id'=>$teacher_ids])->asArray()->all();
        foreach ($teacher_list as $key=>$item){
            $classIds = ClassManageTeacher::find()->select('class_id')->where(['teacher_id'=>$item['id']])->column();
            $count = $this->getCount($classIds,$start,$end);
            $teacher_list[$key]['count'] = $count; //总人数
            $teacher_list[$key]['appointmentCount'] = count($this->getCounttype($classIds,'appointment',$start,$end)); //预约人数
            $renewCount = count($this->getCounttype($classIds,'renew',$start,$end)); //预约人数
            $teacher_list[$key]['renewCount'] = $renewCount; //预约人数
            $teacher_list[$key]['renewalrate'] = 0;
            if($count > 0 && $renewCount>0){
                $teacher_list[$key]['renewalrate'] = round($renewCount/$count,4)*100 .'%';
            }
            $retreatcount = $this->getRetreatcount($classIds,$start,$end);
            $teacher_list[$key]['retreatcount'] = $retreatcount; //退课人数
        }

        return $this->render('view', ['data' => $teacher_list]);
    }

    public function actionClassmanage(){
        $get = \Yii::$app->request->get();
          $id = \Yii::$app->request->get('id');
          $classIds = ClassManageTeacher::find()->select('class_id')->where(['teacher_id'=>$id])->column();
          $classList = ClassManage::find()->where(['class_id'=>$classIds])->asArray()->all();
        $start = !empty($get['satrtdate'])?strtotime(trim($get['satrtdate'])):0;
        $end = !empty($get['enddate'])?strtotime(trim($get['enddate'])."+1 day"):0;
          foreach ($classList as $key=>$class){
              $classAttr = ClassManageAttribute::find()->where(['class_id'=>$class['class_id']])->one();
              $classList[$key]['class_name'] = $classAttr->course; //课程名称
              $count = $this->getCount($class['class_id'],$start,$end);
              $classList[$key]['count'] = $count; //总人数
              $classList[$key]['appointmentCount'] = count($this->getCounttype($class['class_id'],'appointment',$start,$end)); //预约人数
              $renewCount = count($this->getCounttype($class['class_id'],'renew',$start,$end)); //预约人数
              $classList[$key]['renewCount'] = $renewCount; //预约人数
              $classList[$key]['renewalrate'] = 0;
              if($count > 0 && $renewCount>0){
                  $classList[$key]['renewalrate'] = round($renewCount/$count,4)*100 .'%';
              }

              $retreatcount = $this->getRetreatcount($class['class_id']);
              $classList[$key]['retreatcount'] = $retreatcount; //
              if($count == 0){
                  unset($classList[$key]);
              }
          }
        return $this->render('classmanage', ['data' => $classList]);

    }

    public function actionClassstudent(){
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        $data = $this->getstudent($id);
        if($data){
            foreach ($data as $key=>$val){
                $student = Student::findOne($val['student_id']);
                $data[$key]['student_name'] = isset($student->name)?$student->name:'';
                $data[$key]['tel'] = isset($student->customer->mobile)?$student->customer->mobile:'';
                $data[$key]['card'] = isset($student->customer->card_id)?$student->customer->card_id:'';
                if($val['order_type'] == 'appointment'){
                    $data[$key]['order_type'] = '奖学金课';
                }else{
                    $data[$key]['order_type'] = '学费课程';
                }

                $data[$key]['okcount'] = StudentCheck::find()->where(['status'=>1,'class_student_id'=>$val['id']])->count();
            }
        }
        return $this->render('classstudent', ['data' => $data]);
    }

    public function getCount($classIds,$start=0,$end=0){
        $model = ClassStudent::find()->where(['status'=>[0,1,2,4,5,6],'class_manage_id'=>$classIds]);
        if($start>0 && $end == 0){
            $ids = $this->getOrderitemsIds($start,0);
            $model->andWhere(['order_sales_id'=>$ids]);
        }
        if($start == 0 && $end >0){
            $ids = $this->getOrderitemsIds(0,$end);
            $model->andWhere(['order_sales_id'=>$ids]);
        }
        if($start > 0 && $end >0){
            $ids = $this->getOrderitemsIds($start,$end);
            $model->andWhere(['order_sales_id'=>$ids]);
        }
        $count = $model->count();
        return $count;
    }

    public function getCounttype($classIds,$order_type='appointment',$start=0,$end=0){
        $model = (new Query())
            ->select(['cs.id'])
            ->from('{{%class_student}} cs')
            ->leftJoin('{{%orders_items}} oi ','oi.id = cs.order_sales_id')
            ->leftJoin('{{%orders}} o','o.id = oi.orders_id')
            ->where(['cs.class_manage_id'=>$classIds,'cs.status'=>[0,1,2,4,5,6],'o.order_type'=>$order_type]);
            if($start > 0 && $end == 0){
                $model->andwhere(['>','o.pay_time',$start]);
            }
            if($start == 0 && $end > 0){
                $model->andwhere(['<','o.pay_time',$end]);
            }
            if($start > 0 && $end > 0){
                $model->andwhere(['between','o.pay_time',$start,$end]);
            }

        $result = $model->all(Fun::getSiteDb());

        return $result;
    }

    public function getRetreatcount($classId,$start=0,$end=0){
        $retreatModel= ClassStudent::find()->where(['class_manage_id'=>$classId,'status'=>4]);
        if($start > 0 && $end == 0){
            $retreatModel->andwhere(['>','end_time',$start]);
        }
        if($start == 0 && $end > 0){
            $retreatModel->andwhere(['<','end_time',$end]);
        }
        if($start > 0 && $end > 0){
            $retreatModel->andwhere(['between','end_time',$start,$end]);
        }
        $retreatcount = $retreatModel->count();
        return$retreatcount;
    }
    public function getstudent($classId){
        $result = (new Query())
            ->select(['cs.*','o.order_type','oir.lesson'])
            ->from('{{%class_student}} cs')
            ->leftJoin('{{%orders_items}} oi ','oi.id = cs.order_sales_id')
            ->leftJoin('{{%orders}} o','o.id = oi.orders_id')
            ->leftJoin('{{%orders_items_relation}} oir','oi.id = oir.orders_items_id')
            ->where(['cs.class_manage_id'=>$classId])
            ->all(Fun::getSiteDb());

        return $result;
    }

//    public function actionUpdateorderrelation(){
//        $lists = OrdersItemsRelation::find()->where(['price_name'=>'奖学金课程','subsidy_money'=>0])->all();
//        foreach ($lists as $val){
//            $price = GoodsPrice::find()->where(['price_name'=>'奖学金课程','goods_id'=>$val->goods_id])->one();
//            if($price != null){
//                $val->subsidy_type = $price->subsidy_type;
//                $val->subsidy_money = $price->subsidy_money;
//                $val->save(false);
//            }
//        }
//    }

    public function actionSettlement(){
        $mList = Mechanic::find()->select(['id','name'])->where(['status'=>1])->asArray()->all();
        foreach ($mList as $k=>$m) {
            $result = (new Query())
                ->select(['oir.*','o.order_type'])
                ->from('{{%orders_items}} oi')
                ->leftJoin('{{%orders}} o ', 'o.id = oi.orders_id')
                ->leftJoin('{{%orders_items_relation}} oir', 'oi.id = oir.orders_items_id')
                ->where(['oi.mechanic_id' => $m['id'], 'o.pay_status' => [1,4]])
                ->all(Fun::getSiteDb());
            $counts = 0;
            if(!empty($result)){
                foreach ($result as $key=>$val){
                     $customer = Customer::findOne($val['customer_id']);
                     $result[$key]['tel'] = isset($customer->mobile)?$customer->mobile:'';
                     $student = Student::findOne($val['student_id']);
                     $result[$key]['student_name'] = isset($student->name)?$student->name:'';
                     $result[$key]['price_name'] = '奖学金课程';
                     $goods = Goods::findOne($val['goods_id']);
                     $result[$key]['goods_name'] = isset($goods->name)?$goods->name:'';
                     $classGoods = ClassManageGoods::find()->where(['goods_id'=>$goods->id])->one();
                     $result[$key]['teacher_name'] = '';
                     $classteacher = ClassManageTeacher::find()->select('teacher_name')->where(['class_id'=>$classGoods->class_id])->column();
                      if(!empty($classteacher)){
                          $result[$key]['teacher_name'] = implode(',',$classteacher);
                      }
                     $ids = ClassLesson::find()->select('lesson_id')->where(['class_id'=>$classGoods->class_id])->andWhere(['<','class_date',1514732400])->column();
                     $count = StudentCheck::find()->where(['order_sales_id'=>$val['orders_items_id'],'status'=>1,'class_lesson_id'=>$ids])->count(); //上课次数
                    if($val['is_scholarship'] == 2){
                        $result[$key]['price_name'] = '续费课程';
                     }
                    $result[$key]['count'] = $count;
                    $counts += $count;
                    if($count == 0){
                        unset($result[$key]);
                    }

                }
            }
            $mList[$k]['counts'] = $counts;
           $mList[$k]['arr'] = $result;
        }

        return $this->render('settlement', ['data' => $mList]);
    }



}